package com.travel.security.provider;

import com.travel.mapper.admin.AdminMapper;
import com.travel.model.entity.auth.Admin;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collections;
//管理员认证提供者 认证管理员 处理认证异常
public class AdminAuthenticationProvider implements AuthenticationProvider {

    private final AdminMapper adminMapper;
    private final PasswordEncoder passwordEncoder;

    public AdminAuthenticationProvider(AdminMapper adminMapper, PasswordEncoder passwordEncoder) {
        this.adminMapper = adminMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) {
            throw new BadCredentialsException("管理员账号不存在");
        }

        if (admin.getStatus() != 1) {
            throw new BadCredentialsException("管理员账号已被禁用");
        }

        if (!passwordEncoder.matches(password, admin.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }

        return new UsernamePasswordAuthenticationToken(
            username,
            null,
            Collections.singletonList(new SimpleGrantedAuthority("ROLE_ADMIN"))
        );
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
} 